import * as vscode from "vscode";
import { nPost, userData } from "@ap/util/request";
import {
  showErrorMessage,
  showInformationMessage,
} from "@ap/util/vscode/message";
import { arenaErrorMsg } from "@ap/util/vscode/errorMsg";
import {
  ConfigurationItem,
  ConfigurationKey,
} from "@ap/util/vscode/setInsConfig";
import path from "path";
import { insertTextAtSelection } from "@ap/util/aiCodeInteraction/menus";
import { $context } from "@ap/extension";
import insertCode from "@ap/util/vscode/insertCode";
import { generatePrompt, getModels } from "@ap/types/aiChatCfg";
import { handleCreateChat } from "./chatDialog";
export let chatjptConfig: ChatjptViewModel | null;
export function setChatjptConfig(context: ChatjptViewModel) {
  chatjptConfig = context;
}

const FORMAT_DOCUMENT_COMMAND = "editor.action.formatDocument";
const DELAY_BEFORE_FORMAT_MS = 10;

export function userDataToChat() {
  const auth = vscode.workspace
    .getConfiguration(ConfigurationItem.USER_CENTER_TOOL)
    .get(ConfigurationKey.ACCOUNT_TOKEN);
  const ua = vscode.workspace
    .getConfiguration(ConfigurationItem.USER_CENTER_TOOL)
    .get(ConfigurationKey.USER_AGNET);
  if (auth && ua && userData) {
    return {
      auth,
      ua,
      userData,
    };
  }
}
export class ChatjptViewModel implements vscode.WebviewViewProvider {
  public static readonly viewType = "chatjpt";

  public view?: vscode.WebviewView;

  async resolveWebviewView(webviewView: vscode.WebviewView) {
    this.view = webviewView;
    webviewView.webview.options = {
      enableScripts: true,
    };
    webviewView.webview.html = this._getHtmlForWebview(webviewView.webview);

    webviewView.webview.postMessage({
      type: "chatModels",
      models: await getModels(),
    });
    webviewView.webview.onDidReceiveMessage(async (message) => {
      if (message.type === "createChat") {
        handleCreateChat(message, (chatMsg, data) => {
          webviewView.webview.postMessage({
            type: "receiveChat",
            data: chatMsg,
            gptChatNewID: message.gptChatNewID,
            gptChatNew: message.gptChatNew,
            userId: data.userData.data?.userId,
            msg: message.msg,
          });
        });
      }
      if (message.type === "errorChat") {
        showErrorMessage(message.msg);
      }
      if (message.type === "copy") {
        vscode.env.clipboard.writeText(message.text);
        showInformationMessage("代码复制成功");
      }
      if (message.type === "insert") {
        insertCode(message.text);
        this.formatDocumentAfterDelay();
      }

      if (message.type === "chatLog") {
        nPost({
          url: "https://box3lab-api.fanhat.cn/v1/chat_completionslog",
          data: {
            uid: message.uid,
            time: message.time,
            dlgtext: message.dlgtext,
            chat: message.chat,
          },
        });
      }

      if (message.type === "sendChat") {
        const data = userDataToChat();
        if (data) {
          let text = "";
          const editor = vscode.window.activeTextEditor;
          if (editor) {
            text = insertTextAtSelection(editor);
          }
          webviewView.webview.postMessage({
            type: "userDataToChat",
            nickname: data.userData.data?.nickname,
            avatar: data.userData.data?.avatar,
            userId: data.userData.data?.userId,
            userData: data.userData,
            userAgnet: data.ua,
            text: text,
          });
        } else {
          showErrorMessage(arenaErrorMsg.LOG_IN_TO_THE_SHINJIMA_ACCOUNT);
        }
      }
    });
  }

  revive(panel: vscode.WebviewView) {
    this.view = panel;
  }

  async formatDocumentAfterDelay(): Promise<void> {
    await new Promise((resolve) => setTimeout(resolve, DELAY_BEFORE_FORMAT_MS));
    await vscode.commands.executeCommand(FORMAT_DOCUMENT_COMMAND);
  }

  private _getHtmlForWebview(webview: vscode.Webview) {
    const stylePathOnDisk = path.join(
      $context.extensionPath,
      "chatjpt_webui",
      "assets",
    );

    return `
<!DOCTYPE html>
<html lang="zh-CH">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="${webview.asWebviewUri(vscode.Uri.file(path.join(stylePathOnDisk, "css", "default.min.css")))}">
    <script src="${webview.asWebviewUri(vscode.Uri.file(path.join(stylePathOnDisk, "js", "tw3.4.5.js")))}"></script>
    <script src="${webview.asWebviewUri(vscode.Uri.file(path.join(stylePathOnDisk, "js", "jquery-3.7.1.min.js")))}"></script>
    <script src="${webview.asWebviewUri(vscode.Uri.file(path.join(stylePathOnDisk, "js", "highlight.min.js")))}"></script>
    <script src="${webview.asWebviewUri(vscode.Uri.file(path.join(stylePathOnDisk, "js", "marked.min.js")))}"></script>
    <script src="${webview.asWebviewUri(vscode.Uri.file(path.join(stylePathOnDisk, "js", "chat.js")))}"></script>
    <style>
        body,
        html {
            overflow: hidden;
            margin: 0;
            padding: 0;
            height: 100%;
        }

        .bg-black {
            background-color: rgb(0 0 0 / 0%) !important;
        }

        ::-webkit-scrollbar {
            width: 10px;
            height: 10px;
        }

        ::-webkit-scrollbar-corner {
            background-color: var(--vscode-editor-background);
        }

        ::-webkit-scrollbar-thumb {
            background-color: var(--vscode-scrollbarSlider-background);
        }

        ::-webkit-scrollbar-thumb:hover {
            background-color: var(--vscode-scrollbarSlider-hoverBackground);
        }

        ::-webkit-scrollbar-thumb:active {
            background-color: var(--vscode-scrollbarSlider-activeBackground);
        }

        ::highlight(find-highlight) {
            background-color: var(--vscode-editor-findMatchHighlightBackground);
        }

        ::highlight(current-find-highlight) {
            background-color: var(--vscode-editor-findMatchBackground);
        }

        .border-box {
            border-top: 1px solid var(--vscode-panel-border);
            background-clip: padding-box, border-box;
            background-origin: padding-box, border-box;
            background-color: var(--vscode-sideBar-background);
        }
        .msg {
            color: white;
            font-size: 13px;
            font-weight: 300;
        }
        .chat-input-row ::placeholder {
            color: var(--vscode-input-foreground);
        }
        .chat-input-row:focus{
            outline-width: 1px;
            outline-style: solid;
            outline-offset: -1px;
            outline-color: var(--vscode-focusBorder);
            transition: none;
        }
        li,h1,h2,h3,h4,h5,h6,ol{
            color:var(--vscode-foreground);
        }
        p {
            color:var(--vscode-foreground);
            white-space: pre-line;
            overflow-wrap: break-word;
            word-break: break-word;
            line-break: anywhere;
        }
        .emoji {  
            font-size: 16px;  
            vertical-align: middle;  
            margin: 0 5px;  
        }  
        .instructions {  
            margin-top: 10px;  
            list-style-type: decimal;  
            padding-left: 20px;  
        }  
        @keyframes spin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }

        .rotate-icon {
            animation: spin 2s linear infinite;
        }
        .codeCard {
            transition: all 0.3s ease;
            border-radius: 5px;
            padding: 4px;
        }   

        .codeCard:hover {
            background-color: rgba(255,255,255,.12);
        }
        .hljs {
            background: #0404043d;
        }
        .labelChat{
            color: #0079e3;
            font-weight: 500;
            margin-bottom: 7px;
        }
        .welcome-message {
          line-height: 1.6;
          color:var(--vscode-foreground);
          max-width: 400px;
          padding: 15px;
          border-radius: 8px;
        }

        .emoji-line {
          font-size: 1.3em;
          margin-bottom: 8px;
        }

        .emoji {
          font-size: 1.2em;
          vertical-align: middle;
        }



        .tip-line {
          margin-top: 12px;
          padding: 10px;
          border-radius: 6px;
          border-left: 4px solid var(--vscode-focusBorder);
        }

    </style>
</head>

<body>
    <div class="h-dvh flex flex-col bg-black" >

        <div class="relative flex h-full flex-col overflow-y-hidden" >
            <div class="flex h-full w-full  flex-col overflow-y-auto pr-2 pl-2 first:pt-2" id="messageContainer" style="margin-bottom: 95px;">

                <div class="mb-2  w-full ">
                    <div class="overflow-hidden break-words p-2 rounded-lg msg" style="background-color: hsla(0, 0%, 100%, .04);">
                        <div class="size-7 order-first aspect-square shrink-0 p-1 rounded-full flex items-center gap-2 "
                            style="width: 100%!important;margin-bottom: 8px;">
                            <img
                                src="${webview.asWebviewUri(vscode.Uri.file(path.join(stylePathOnDisk, "img", "jpt.svg")))}">
                            <p>Chat吉PT</p>
                        </div>
                    <div class="welcome-message">
  <div class="emoji-line">
    <span class="emoji">👋</span> 嗨！<span class="emoji">🤖</span> 我是 <strong>Chat吉PT</strong>
  </div>
  <div class="description-line">
    专注于 <strong>TypeScript</strong> 与 <strong>神岛API</strong> 教学
  </div>
  <div class="tip-line">
    💡 在其他平台的 <span class="tag">AI Agent模式</span> 下<br>
    你可以通过 <code>ap_chatjpt_onlyKnowledgeBase</code> 命令<br>
    调用我的知识库哦～
  </div>
</div>

                    </div>
                </div>

 

            </div>
             
            <div class="absolute bottom-0 left-0 right-0">
          
                <div class="border-box">
                  <div style="   border-radius:0.3rem;  margin: 11px;   background-color: var(--vscode-input-background);">
                    <select  id="chatOptions" style="     max-width: 80%;width: 230px;   outline-color: transparent;height: 23px;max-height:300px; margin-top: 0.4rem;padding-left: 0.4rem; padding-right: 8px;border-radius: 0.3rem;background-color:var(--vscode-input-background); color:var(--vscode-disabledForeground); ">
                   
                    </select>
                     <button onclick="sendChat()" class="cursor-pointer rounded-full h-full " style="position: absolute;right: 0;margin-right: 20px;height: 35px;" id="sendButton">
                            <svg t="1721465995786" class="icon" viewBox="0 0 1879 1024" version="1.1"
                                xmlns="http://www.w3.org/2000/svg" p-id="5233" width="24" height="24">
                                <path
                                    d="M1528.305202 490.543353l-415.815029-417.146821c-9.47052-9.47052-21.900578-14.649711-35.366474-14.649711-13.465896 0-26.043931 5.327168-35.662427 14.797688-18.053179 18.201156-19.828902 46.46474-4.143353 66.441618l338.275145 339.310983h-988.48555c-27.523699 0-50.016185 22.492486-50.016185 50.312139 0 27.671676 22.492486 50.312139 50.016185 50.312138h988.48555L1029.031214 927.371098c-10.358382 20.716763-7.250867 44.689017 8.434682 60.22659 9.322543 9.322543 21.900578 14.353757 35.514451 14.353757 14.945665 0 29.151445-6.067052 40.101734-16.869364l27.671676-27.671676 76.208093-76.35607 14.353757-14.057803 296.989595-298.025434c9.766474-9.914451 14.797688-23.380347 14.057804-38.178034v-2.071677c0.739884-14.797688-4.291329-28.411561-14.057804-38.178034m0 0z"
                                    fill="#bfbfbf" p-id="5234"></path>
                            </svg>
                        </button>
                    <div class="flex w-full   gap-2 " style="align-items: flex-end;padding-right: 0;padding-left: 0.7rem;">
                        <textarea  maxlength="5000" rows="1" id="chatjptChat" type="text" placeholder="输入你的问题..."
                            style="padding-right: 10px;outline-color: transparent; max-height:300px; margin-top: 8px;padding-bottom: 8px;background-color:var(--vscode-input-background);border-radius: 0.3rem; color: var(--vscode-input-foreground); "
                            class="chat-input-row resize-none grow appearance-none text-white outline-none "></textarea>
                       
                    </div>
                  </div>
                </div>
            </div>
        </div>
    </div>
    <script>

function r_ac(element) {
    n = $(element).data('n');
    if(!n){
     $(element).data({ n: 0 });
     n = 0;
    }
    if (n % 2 == 0) {
      $(element).next().hide(500);
    } else {
      $(element).next().show(500);
    }
    $(element).data({ n: n + 1 });
  };



        var inputBox = document.getElementById('chatjptChat');
        var sendButton = document.getElementById('sendButton');
        const vscode = acquireVsCodeApi();
        function sendChat() {
            vscode.postMessage({
                type: 'sendChat'
            })
        }
        document.addEventListener('keydown', function (event) {
            if (event.key === 'Enter') {
                    if (!event.shiftKey) {
                    event.preventDefault();
                       sendChat()
                    }
            }
        });
        window.addEventListener('message', (event) => {
            if(event.data.type =='chatModels'){
                const select = document.getElementById('chatOptions');
                if (!event.data.models || event.data.models.length == 0 || event.data.models == 0) {
                    select.style.display = 'none';
                }
                Object.entries(event.data.models).forEach(([key, value]) => {
                    const option = document.createElement('option');
                    option.value = value;
                    option.text = key;
                    select.appendChild(option);
                });
             
            }

            if(event.data.type =='receiveChat'){
                onMsg(
                  event.data.data,
                  event.data.gptChatNew,
                  event.data.gptChatNewID,
                  event.data.userId,
                  event.data.msg,
                );
            }
        
            if(event.data.type =='userDataToChat'){
                chat(
                    event.data.userData,
                    event.data.userAgnet,
                    event.data.nickname,
                    event.data.avatar,
                    '${webview.asWebviewUri(vscode.Uri.file(path.join(stylePathOnDisk, "img", "jpt.svg")))}',
                    '',
                    0,
                    event.data.text,
                    document.getElementById('chatOptions').value
                );
            }
            if(event.data.type =='postFastChat'){
                chat(
                    event.data.userData,
                    event.data.userAgnet,
                    event.data.nickname,
                    event.data.avatar,
                    '${webview.asWebviewUri(vscode.Uri.file(path.join(stylePathOnDisk, "img", "jpt.svg")))}',
                    event.data.labelChat,
                    event.data.typeChat,
                    event.data.text,
                    document.getElementById('chatOptions').value
                );
            }
        });
        inputBox.addEventListener('input', autoResize);
        window.addEventListener('resize', autoResize);
        function autoResize() {
            inputBox.style.height = 'auto';
            inputBox.style.height = inputBox.scrollHeight + 'px';
        }
        autoResize();

        
    </script>
</body>

</html>`;
  }
}
